const MAX_HEIGHT = screen.width * .66667;

const vm = new Vue({
    el: '#main',
    data: {
        shareBoxShow: false,
        height: MAX_HEIGHT,
        house: {
            oneComment: {
                tenant: {
                    info: {},
                    recomment: {
                        content: '',
                    },
                },
            },
            officialDiscount: {
                start_date: '',
                end_date: '',
                discount: '',
            },
        },
        nearHouse: [],
        hasSome: (() => {
            const arr = [{
                'name': '汽车',
                'style': 'icon-qiche',
                'facility_id': 0,
            }, {
                'name': '导游 ',
                'style': 'icon-daoyou',
                'facility_id': 35,
            }, {
                'name': '接送机',
                'style': 'icon-jiesongji',
                'facility_id': 34,
            }, {
                'name': '娱乐，E家',
                'style': 'icon-yule1',
                'facility_id': 0,
            }, {
                'name': '搭配套餐',
                'style': 'icon-canpan',
                'facility_id': 0,
            }, {
                'name': '娱乐活动',
                'style': 'icon-yulexiuxian',
                'facility_id': 0,
            }, {
                'name': '娱乐_电影',
                'style': 'icon-yuledianying',
                'facility_id': 0,
            }, {
                'name': '可带宠物',
                'style': 'icon-ichongwu',
                'facility_id': 26,
            }, {
                'name': '允许做饭',
                'style': 'icon-webiconyunxuzuofan',
                'facility_id': 25,
            }, {
                'name': '允许吸烟',
                'style': 'icon-webiconyunxuxiyan',
                'facility_id': 24,
            }, {
                'name': '允许聚会',
                'style': 'icon-juhuihongpa',
                'facility_id': 27,
            }, {
                'name': '24小时热水',
                'style': 'icon-xiaoshireshui',
                'facility_id': 28,
            }, {
                'name': '手纸',
                'style': 'icon-shouzhi',
                'facility_id': 9,
            }, {
                'name': '毛巾',
                'style': 'icon-maojin',
                'facility_id': 10,
            }, {
                'name': '牙具',
                'style': 'icon-yaju',
                'facility_id': 6,
            }, {
                'name': '洗发露',
                'style': 'icon-xifalu',
                'facility_id': 11,
            }, {
                'name': '淋浴',
                'style': 'icon-linyu',
                'facility_id': 5,
            }, {
                'name': '拖鞋',
                'style': 'icon-tuoxie',
                'facility_id': 8,
            }, {
                'name': '浴缸',
                'style': 'icon-yugang',
                'facility_id': 12,
            }, {
                'name': '香皂',
                'style': 'icon-xiangzao',
                'facility_id': 7,
            }, {
                'name': '沐浴露',
                'style': 'icon-muyulu',
                'facility_id': 11,
            }, {
                'name': '智能门锁',
                'style': 'icon-zhinengmensuo',
                'facility_id': 0,
            }, {
                'name': '电梯',
                'style': 'icon-dianti',
                'facility_id': 21,
            }, {
                'name': '停车位',
                'style': 'icon-tingchewei',
                'facility_id': 22,
            }, {
                'name': '门禁系统',
                'style': 'icon-menjinxitong',
                'facility_id': 23,
            }, {
                'name': '空调',
                'style': 'icon-kongtiao',
                'facility_id': 14,
            }, {
                'name': '电脑',
                'style': 'icon-diannao',
                'facility_id': 0,
            }, {
                'name': '无线网络',
                'style': 'icon-wuxianwangluo',
                'facility_id': 18,
            }, {
                'name': '电视',
                'style': 'icon-dianshi',
                'facility_id': 13,
            }, {
                'name': '有线网络',
                'style': 'icon-youxianwangluo',
                'facility_id': 19,
            }, {
                'name': '微波炉',
                'style': 'icon-weibolu',
                'facility_id': 0,
            }, {
                'name': '暖气',
                'style': 'icon-nuanqi',
                'facility_id': 20,
            }, {
                'name': '饮水机',
                'style': 'icon-yinshuiji',
                'facility_id': 15,
            }, {
                'name': '冰箱',
                'style': 'icon-bingxiang',
                'facility_id': 16,
            }, {
                'name': '洗衣机',
                'style': 'icon-xiyiji',
                'facility_id': 17,
            }, ];
            const idMap = new Map();
            forEach(arr, e => {
                idMap.set(e.facility_id.toString(), e);
            });
            return idMap;
        })(),
    },
    methods: {
        toggleTextEll,
        toggleTextEll2,
        reloadPageById,
        collectHouse,
        share,
        goPage,
        shareWX,
        shareQQ,
    },
    components: {},
    updated() {
        updateSlider();
    },
    mounted() {
        document.getElementById('popupDateBox').style.display = '-webkit-flex';
    },
});

const vmFooter = new Vue({
    el: 'footer',
    data: {
        house: {},
    },
    methods: {
        goPage,
        datePopupShow,
        chatting,
    },
});

function setGallery() {
    const gallery = mui('#banner-gallery');
    gallery.slider({
        interval: 0,
    });
}

function toggleTextEll(e) {
    document.querySelector('p.description').classList.toggle('text-ell');
    document.querySelector('div.allow-something').classList.toggle('allow-wrap');
}

function setMapLocation() {
    const mapElement = document.getElementById('map');
    mapElement.style.height = mapElement.offsetWidth * 0.5625 + 'px';
}

function initMap() {
    const map = showMap('map', {
        zoomLv: 15,
        drag: false,
        zoom: false,
    });
    map.addEventListener('click', () => {
        popupBigMap();
    });
}

function toggleTextEll2(className) {
    document.querySelector(className).classList.toggle('text-ell');
}

function popupBigMap() {
    const popup = document.getElementById('bigMapPopup');
    popup.style.display = 'block';

    const map = showMap('bigMap', {
        lng: vm.house.lng,
        lat: vm.house.lat,
        zoomLv: 14,
    });
    const closeBtn = document.getElementById('bigMapClose');
    closeBtn.onclick = () => {
        popup.style.display = 'none';
    };

    const geolocationControl = new BMap.GeolocationControl();
    geolocationControl.addEventListener('locationSuccess', function (e) {
        // 起点
        const p1 = new BMap.Point(e.point.lng, e.point.lat);
        // 终点
        const p2 = new BMap.Point(vm.house.lng, vm.house.lat);

        const driving = new BMap.DrivingRoute(map, {
            renderOptions: {
                map: map,
                autoViewport: true,
            },
        });
        driving.search(p1, p2);
    });
    geolocationControl.addEventListener('locationError', function (e) {
        // 定位失败事件
        toast(e.message);
    });
    map.addControl(geolocationControl);
}

function showMap(elemId, {
    lng = vm.house.lng,
    lat = vm.house.lat,
    zoomLv = 13,
    drag = true,
    zoom = true,
} = {}) {
    const map = new BMap.Map(elemId); // 创建Map实例
    map.centerAndZoom(new BMap.Point(lng, lat), zoomLv); // 初始化地图,设置中心点坐标和地图级别
    map.enableScrollWheelZoom(zoom);
    if (!drag) {
        map.disableDragging();
    }
    const marker = new BMap.Marker(new BMap.Point(lng, lat)); // 创建点
    map.addOverlay(marker);
    return map;
}

function getHouseId() {
    const houseId = fxj.getSearch().get('id');
    getHouseId = () => houseId;
    return houseId;
}

async function getHouseInfo() {
    const houseId = getHouseId();
    if (!houseId) return;
    const close = fxj.dialog.loading({
        noBg: true,
    });
    const result = await ajax({
        url: 'home/houseDetail/getHouseCommentDetail',
        type: 'POST',
        data: {
            houseId,
        },
    });
    close();
    if (result.err !== 0) {
        toast(result.msg);
        return;
    }
    result.data.img = fxj.fixImgUrl(result.data.img);
    forEach(result.data.imgs, img => {
        img.surl = fxj.fixImgUrl(img.surl);
        img.url = fxj.fixImgUrl(img.url);
    });
    if (
        result.data &&
        result.data.oneComment &&
        result.data.oneComment.tenant &&
        result.data.oneComment.tenant.recomment
    ) {
        result.data.oneComment.tenant.info.photo = fxj.fixImgUrl(result.data.oneComment.tenant.info.photo);
    }
    vm.house = result.data;
    vmFooter.house = result.data;
    vm.house.bedCount = vm.house.bed.count;
    vm.house.bedList = vm.house.bed.list;
    vm.house.cCountList = vm.house.cCount.list;
    vm.house.cCountCount = vm.house.cCount.count;
    vm.house.cCountScore = vm.house.cCount.score ? vm.house.cCount.score : 0;
    vm.house.starTotal = ~~vm.house.starTotal;
    setFooterData(vm.house);
    initMap();
    setTimeout(() => {
        setGallery();
        canShowImg();
    }, 0);
}

function setFooterData(data) {
    const footer = document.querySelector('footer');
    footer.querySelector('.avatar').src = data.photo;
    footer.querySelector('#userName').innerHTML = data.nickname;
    let svg = null;
    if (data.gender === '0') {
        svg = `<svg class="icon icon-sex-0" aria-hidden="true">
                    <use xlink:href="#icon-sex-woman"></use>
                </svg>`;
    } else {
        svg = `<svg class="icon icon-sex-1" aria-hidden="true">
                    <use xlink:href="#icon-sex-man"></use>
                </svg>`;
    }
    footer.querySelector('#gender').outerHTML = svg;
}

async function getNearbyHouse() {
    const result = await ajax({
        url: 'home/houseDetail/getNearbyHouse',
        type: 'POST',
        data: {
            houseId: getHouseId(),
        },
    });
    if (!result.data ||
        !result.data.houseData ||
        result.data.houseData.length <= 0
    ) {
        return;
    }
    forEach(result.data.houseData, house => {
        house.img = fxj.fixImgUrl(house.img);
    });
    vm.nearHouse = result.data.houseData;
}

function updateSlider() {
    mui('#nearHouse').slider({
        interval: 0,
    });
    forEach(document.querySelectorAll('#nearHouse .house-img'), img => {
        img.height = img.width / 3 * 2;
    });
}

// 根据houseId重新加载页面
function reloadPageById(id) {
    location.href = `house_res_detail.html?id=${id}`;
}

// 日期选择框框
const vmPopupDateBox = new Vue({
    el: '#popupDateBox',
    data: {
        selectDateList: [],
        dateList: [],
        dayLength: 0,
        choosable: false,
        selectDate: {
            start: '--',
            startDay: null,
            end: '--',
            endDay: null,
            nightNum: '--',
            todayIndex: 0,
            firstYet: null,
        },
        popupShow: false,
    },
    method: {},
});

function main() {
    fxj.fixStatusBar('header', 5);
    document.getElementById('banner-gallery').addEventListener('touchend', () => {
        canShowImg();
    });
    setTimeout(() => {
        getNearbyHouse();
    }, 3500);
    getHouseInfo();
    setMapLocation();

    initSelectDateBox.call(vmPopupDateBox);
}

if (fxj.deBug) {
    main()
}

function apiready() {
    main()
}

function datePopupShow() {
    vmPopupDateBox.popupShow = true;
}

function closeDatePopup() {
    vmPopupDateBox.popupShow = false;
    const html = document.querySelector('html');
    html.classList.remove('no-scroll');
    closeDatePopup = () => {
        vmPopupDateBox.popupShow = false;
        html.classList.remove('no-scroll');
    };
}

async function initSelectDateBox() {
    // 请求服务器获取房源日期列表
    const data = await getHouseResDateInfo();
    let tempDataArr = []; // 不这么绕一圈,vue监听不到数据变化  囧
    // 把原始数据格式化为需要格式
    forEach(data, (month, monthIndex) => {
        tempDataArr[monthIndex] = {
            date: '', // 当前 年-月
            startWeek: 0, // 当月第一天星期几
            child: [] // 当月的所有日期
        };
        forEach(month, (day, dayIndex) => {
            const dayInfo = {
                // 使vue监听数据
                year: day.date.substr(0, 4),
                month: (+day.date.substr(4, 2)).toString(),
                day: (+day.date.substr(6, 2)).toString(),
                price: day.discount_price === 0 ? day.price : day.discount_price,
                yet: +day.is_rent !== 0, // 当天已租?
                week: day.week,
                index: this.dayLength, // 线性表索引
                start: false,
                mid: false,
                end: false,
            };
            // 日期是否已经过期
            dayInfo.outmoded =
                new Date(`${dayInfo.year}/${dayInfo.month}/${dayInfo.day}`) -
                getToday();
            if (dayInfo.outmoded === 0) {
                this.selectDate.todayIndex = dayInfo.index;
            }
            dayInfo.ban = dayInfo.yet || dayInfo.outmoded < 0; // 当天不可选?

            tempDataArr[monthIndex].child[dayIndex] = dayInfo;
            tempDataArr[monthIndex].date = `${dayInfo.year}-${dayInfo.month}`;
            dayIndex === 0 && (tempDataArr[monthIndex].startWeek = dayInfo.week);
            this.dayLength++;
        });
        this.selectDateList = this.selectDateList.concat(tempDataArr[monthIndex].child);
    });
    vmPopupDateBox.dateList = tempDataArr;
}

function getToday() {
    const t = new Date(new Date().toLocaleDateString());
    getToday = () => t;
    return t;
}

function select(day) {
    if (vmPopupDateBox.selectDate.start === '--') {
        setSelectDay(day, 'start');
        const schipolDay = findSchipolHouse(day.index); // 找到第一个不可租
        if (schipolDay) {
            changeSchipolHouseStatus(schipolDay);
            setBanElem(day.index, schipolDay.index);
        } else {
            setBanElem(day.index, -1);
        }
    } else if (
        day.index !== vmPopupDateBox.selectDate.startDay.index &&
        vmPopupDateBox.selectDate.end === '--'
    ) {
        setSelectDay(day, 'end');
        setMidEl(vmPopupDateBox.selectDate);
        setNieghtNum(
            vmPopupDateBox.selectDate.startDay.index,
            vmPopupDateBox.selectDate.endDay.index,
        );
    } else if (vmPopupDateBox.selectDate.end !== '--') {
        clearSelectedDate();
        clearTempBan();
    }
}

async function getHouseResDateInfo() {
    const date = new Date();
    const res = await ajax({
        type: 'POST',
        url: 'home/houseDetail/getMonthPriceStatus',
        data: {
            houseId: getHouseId(),
            time: `${date.getFullYear()}/${date.getMonth()}/1`,
        },
    });
    if (res.err !== 0) {
        toast(res.msg);
    }
    return res.data;
}

function setSelectDay(day, type) {
    vmPopupDateBox.selectDate[type] = `${day.month}月${day.day}日`;
    vmPopupDateBox.selectDate[`${type}Day`] = day;
    day[type] = true;
}

function findSchipolHouse(i) {
    const el = vmPopupDateBox.selectDateList[i];
    if (!el) return null;
    if (el.yet) return el;
    return findSchipolHouse(++i);
}

function changeSchipolHouseStatus(day) {
    vmPopupDateBox.selectDate.firstYet = day;
    day.ban = false;
}

function setBanElem(startEl, rightStartEl) {
    while (true) {
        startEl--;
        if (vmPopupDateBox.selectDateList[startEl]) {
            vmPopupDateBox.selectDateList[startEl].ban = true;
        } else {
            break;
        }
    }

    if (rightStartEl !== -1) {
        while (true) {
            rightStartEl++;
            if (vmPopupDateBox.selectDateList[rightStartEl]) {
                vmPopupDateBox.selectDateList[rightStartEl].ban = true;
            } else {
                break;
            }
        }
    }
}

function setMidEl(selectDate) {
    let [start, end] = [selectDate.startDay.index, selectDate.endDay.index];
    start++;
    for (; start < end; start++) {
        vmPopupDateBox.selectDateList[start].mid = true;
    }
}

function setNieghtNum(start, end) {
    vmPopupDateBox.selectDate.nightNum = `${end - start}晚`;
}

function clearSelectedDate() {
    vmPopupDateBox.selectDate.start = '--';
    vmPopupDateBox.selectDate.end = '--';
    vmPopupDateBox.selectDate.nightNum = '--';
    vmPopupDateBox.selectDate.startDay.start = false;
    vmPopupDateBox.selectDate.endDay.end = false;
    let start = vmPopupDateBox.selectDate.startDay.index + 1;
    let end = vmPopupDateBox.selectDate.endDay.index;
    while (start < end) {
        vmPopupDateBox.selectDateList[start].mid = false;
        start++;
    }
    vmPopupDateBox.selectDate.startDay = null;
    vmPopupDateBox.selectDate.endDay = null;
}

function clearTempBan() {
    let i = vmPopupDateBox.selectDate.todayIndex;
    let end = vmPopupDateBox.selectDateList.length;
    while (i < end) {
        if (!vmPopupDateBox.selectDateList[i].yet) {
            vmPopupDateBox.selectDateList[i].ban = false;
        }
        i++;
    }
    if (vmPopupDateBox.selectDate.firstYet) {
        vmPopupDateBox.selectDate.firstYet.ban = true;
        vmPopupDateBox.selectDate.firstYet = null;
    }
}

function collectHouse(house) {
    if (house.isCollect === 1) {
        house.isCollect = 0;
    } else {
        house.isCollect = 1;
    }
    fxj.api.collectHouse(house.id).then(res => {
        mui.toast(res.msg);
    });
}

function chatting(id, house) {
    if (!localStorage.getItem('token')) {
        goPage('log_in.html');
    } else {
        goPage('chat.html', {
            data: {
                landlordId: id,
                houseId: getHouseId(),
            },
        });
    }
}

function share() {
    vm.shareBoxShow = true;
}

function shareWX(type) {
    closeShareBox();
    const wx = api.require('wx');
    wx.shareWebpage({
            scene: type,
            title: vm.house.title,
            description: vm.house.title,
            thumb: vm.house.img,
            contentUrl: `http://mfxj.fxj178.com/home/houseDetail/HouseDetail?id=${getHouseId()}`,
        },
        function (ret, err) {
            if (ret.status) {
                toast('分享成功');
            }
        },
    );
}

function shareQQ(type) {
    closeShareBox();
    const qq = api.require('qq');
    qq.shareNews({
            url: `http://mfxj.fxj178.com/home/houseDetail/HouseDetail?id=${getHouseId()}`,
            title: vm.house.title,
            description: vm.house.title,
            imgUrl: vm.house.img,
            type,
        },
        ret => {
            if (ret.status) {
                toast('分享成功');
            }
        },
    );
}

function shareWeiBo() {
    closeShareBox();
    const weibo = api.require('weibo');
    weibo.shareWebPage({
            text: vm.house.title,
            title: vm.house.title,
            description: vm.house.title,
            thumb: vm.house.img,
            contentUrl: `http://mfxj.fxj178.com/home/houseDetail/HouseDetail?id=${getHouseId()}`,
        },
        function (ret, err) {
            if (ret.status) {
                toast('分享成功');
            }
        },
    );
}

function closeShareBox() {
    vm.shareBoxShow = false;
}

function nowReserveHouse() {
    if (!localStorage.getItem('token')) {
        goPage('log_in.html');
    } else {
        goPage('book_room.html', {
            data: {
                id: getHouseId(),
            },
        });
    }
}

function canShowImg() {
    const divList = document.querySelectorAll('#banner-gallery .mui-slider-item .img-bg-container div[data-url]');
    forEach(divList, div => {
        fxj.isContainElement(div, div => {
            div.style.backgroundImage = `url(${div.getAttribute('data-url')})`;
            div.removeAttribute('data-url');
        });
    });
}